import api from '@/api'

// 学生端tabBar显示
function setSTabBar(){
    uni.setTabBarItem({index: 0,visible: false})
    uni.setTabBarItem({index: 1,visible: true})
    uni.setTabBarItem({index: 2,visible: true})
    uni.setTabBarItem({index: 3,visible: true})
    uni.setTabBarItem({index: 4,visible: false})
    uni.setTabBarItem({index: 5,visible: true})
}

// 老师端tabBar显示
function setTTabBar(){
    uni.setTabBarItem({index: 0,visible: true})
    uni.setTabBarItem({index: 1,visible: false})
    uni.setTabBarItem({index: 2,visible: true})
    uni.setTabBarItem({index: 3,visible: true})
    uni.setTabBarItem({index: 4,visible: true})
    uni.setTabBarItem({index: 5,visible: false})
}
// 弹窗背景
let transitionStyles = {
    bg: {
        position: 'fixed', 
        top: 0, 
        /* #ifdef H5 */
        left: 'var(--window-left)',
        right: 'var(--window-right)',
        /* #endif */
        /* #ifndef H5 */
        left: 0,
        right: 0,
        /* #endif */
        height: '100%', 
        background: 'rgba(0, 0, 0, .6)', 
        'z-index': 9
    },
    fade: {
        position: 'absolute',
        'z-index': 10
    }
}

// 任务、活动 文件显示
function xiaodeShowFiles(list, index, dataList, that, item){
    list = JSON.parse(list)
    let imgs = [], files = [], dst_files = [], video_list = []
    for(let i=0; i<list.length; i++){
        if(list[i].msgType==8){
            files.push(list[i].path)
            dst_files.push(list[i])
        }else if(list[i].msgType==3){
            video_list.push(that.api.xiaodeObsUrl+list[i].path)
        }else if(list[i].msgType==1){
            imgs.push(`${that.api.xiaodeObsUrl}${list[i].path}`)
        }
        
    }
    if(index == -1){
        
        if(imgs.length>0){
            that.$set(dataList, 'dst_imgs', imgs)
        }
        if(files.length>0){
            that.$set(dataList, 'files_show', dst_files)
        }
        if(video_list.length>0){
            that.$set(dataList, 'video_list', video_list)
            // downvideoFile(video_list[0], index, dataList, that)
        }
        return
    }
    let obj = dataList[index]
    let infoData = item?item:obj
    if(imgs.length>0){
        infoData.dst_imgs = imgs
    }
    if(files.length>0){
        infoData.files_show = dst_files
    }
    if(video_list.length>0){
        infoData.video_list = video_list
        
        // downvideoFile(video_list[0], index, dataList, that)
    }
    
    that.$set(dataList, index, obj)
}

// 聊天页面文件缓存
function getFileDownloadUrl(data, that){

    let content = data.content
    if(data.msgType == 8){
        let list = JSON.parse(data.content), conts = []
        for(let i=0; i<list.length; i++){
            conts.push(list[i].path)
        }
        content = JSON.stringify(conts)
    }else if(data.msgType == 2){
        content = JSON.stringify([JSON.parse(data.content)[0].path])
    }
    that.api.get('file/getDownloadUrl', {
        fileNames: content,
        isThumbnail: data.msgType==1?true:false
    }).then(res=>{
        if(res.data.state != 'ok') return
        let downloadUrl = res.data.downloadUrl || {},
        urls = [];
        urls = Object.values(downloadUrl)
        
        let extras = JSON.parse(data.extras);
        extras.dst_path = extras.dst_path?extras.dst_path:[]
        // #ifdef APP-PLUS || H5
        for(let i=0; i<urls.length; i++){
            downloadFileFun(data, urls[i],extras, that)
        }
        
        // #endif
    })
}
function downloadFileFun(data, downloadUrl, extras, that){
    uni.downloadFile({
        url: downloadUrl, //资源
        success: (res) => {
            if (res.statusCode === 200) {
                // console.log('下载成功', res);
                function fun(path){
                    extras.dst_path.push(path)
                    that.$set(data, 'extras', JSON.stringify(extras))
                    let tableName = data.groupId?'togroupmsg':that.toUserType==1?'totmsg':'tosmsg'
                    getApp().globalData.mysql.update(tableName, data, function(res){
                        // console.log(131,data,tableName, res)
                    })
                }
                // #ifdef H5
                fun(res.tempFilePath)
                // #endif
                // #ifdef APP-PLUS
                uni.saveFile({
                    tempFilePath: res.tempFilePath,
                    success: (res1)=>{
                        let dst_path = plus.io.convertLocalFileSystemURL(res1.savedFilePath)
                        fun(dst_path)
           
                    }
                })
                // #endif
            }
        }
    });
}

// 聊天列表时间显示规则
function handleTs(time, type){
    if(!time>0) return ''
    let date = new Date(time), str = '';
    let year = date.getFullYear(), month = date.getMonth(), day = date.getDate();
    // 当前时间
    let curYear = new Date().getFullYear(), 
        curMonth = new Date().getMonth(), curDay = new Date().getDate();

    let h = date.getHours();
        h = h < 10 ? `0${h}` : h;
        let m = date.getMinutes();
        m = m < 10 ? `0${m}` : m;
        
    let timeStamp = new Date(`${year}/${month}/${day}`).getTime(), 
        timeStamp2 = new Date(`${curYear}/${curMonth}/${curDay}`).getTime(),
        diff = timeStamp2-timeStamp;
    if(diff <= 24*60*60*1000&&day==curDay){
        str = `${h}:${m}`
    }else if(year == curYear){
        str = type=='his'?`${month+1}-${day}`:`${month+1}月${day}日`
    }else {
        str = type=='his'?`${year}-${month+1}-${day}`:`${year}年${month+1}月${day}日`
    }
    return str
}

// 聊天页面的时间显示规则
function handleDetailsTs(time){
    if(!time>0) return ''
    let date = new Date(time), str = '';
    let year = date.getFullYear(), month = date.getMonth(), day = date.getDate();
    // 当前时间
    let curYear = new Date().getFullYear(), 
        curMonth = new Date().getMonth(), curDay = new Date().getDate();

    let h = date.getHours();
        h = h < 10 ? `0${h}` : h;
        let m = date.getMinutes();
        m = m < 10 ? `0${m}` : m;
    let s = date.getSeconds();
        s = s < 10 ? `0${s}` : s;
    
    let timeStamp = new Date(`${year}/${month}/${day}`).getTime(), 
        timeStamp2 = new Date(`${curYear}/${curMonth}/${curDay}`).getTime(),
        diff = timeStamp2-timeStamp;
    if(diff <= 24*60*60*1000&&day==curDay){
        str = `${h}:${m}:${s}`
    }else if(year == curYear){
        str = `${month+1}月${day}日  ${h}:${m}:${s}`
    }else {
        str = `${year}年${month+1}月${day}日 ${h}:${m}:${s}`
    }
    return str
}

// 传时间new Date() 获取到2022-01-01格式的日期
function initDateDay(t){
    let date = t?t:new Date();
    let Mon = date.getMonth()+1;
    Mon = Mon>9?Mon:`0${Mon}`;
    let day = date.getDate();
    day = day>9?day:`0${day}`
    this.pickerDate = date.getFullYear()+'-'+Mon+'-'+day;
    return date.getFullYear()+'-'+Mon+'-'+day
}

// 传2022-01-01格式的日期，获取到2022年01月01格式的日期
function dateFormat(date){
    let array = date.split('-');
    if(array.length!=3){
        return ''
    }
    return array[0]+'年'+array[1]+'月'+array[2]
}

// 根据当前日期，计算出是第几周
function getWeek(dt){ 
    let d1 = new Date(dt);
    let d2 = new Date(dt);
    d2.setMonth(0);
    d2.setDate(1);
    let oneWeek = d2.getDay();
    oneWeek = oneWeek==0?7:oneWeek
    let rq = d1-d2;
    let days = Math.ceil(rq/(24*60*60*1000));
    let num = parseInt((oneWeek+days-1)/7);// 从0开始
    return num;
}

// H5消息提示框
function msgPopup(avatarUrl, text, name, path){
    let deletenode = document.getElementsByClassName('message-prompt')[0]
    if(deletenode){
        
        document.body.removeChild(deletenode);
    }
    let node = document.createElement('view');
    node.setAttribute("class","message-prompt")
    let str = `<view class="mp-item xd-box-shadow">
        <image class="head" src="${avatarUrl}" mode="center"></image>
        <view class="cont">
            <text class="name">${name}</text>
            <view class="text">
                ${text}
            </view>
        </view>
    </view>`
    node.addEventListener("click", (e) => {
        if(path.indexOf('parmas=tabBar')!=-1){
            uni.switchTab({
                url: path,
                success: ()=>{
                    let node = document.getElementsByClassName('message-prompt')[0]
                    if(node){
                        
                        document.body.removeChild(node);
                    }
                }
            })
        }else{
            if(path.indexOf('params=redirect')!=-1){
                uni.redirectTo({
                    url: path,
                    success: ()=>{
                        let node = document.getElementsByClassName('message-prompt')[0]
                        if(node){
                            document.body.removeChild(node);
                        }
                    }
                })
            }else{
                uni.navigateTo({
                    url: path,
                    success: ()=>{
                        let node = document.getElementsByClassName('message-prompt')[0]
                        if(node){
                            document.body.removeChild(node);
                        }
                    }
                })
            }
            
        }
        
    }, false);
    node.innerHTML += str;
    document.body.appendChild(node);
    setTimeout(()=>{
        let nodeMp = document.getElementsByClassName('message-prompt')[0]
        if(nodeMp){
            getApp().globalData.taskPageIndex = -1
            document.body.removeChild(nodeMp);
        }
        
    }, 5000)
}

// 获取历史记录的时候去重
function deDuplication(list, newList, sessionId, wsFromId, toUserType){
    let arr = list.concat(newList);
    let newArr = []
    for(let i=0; i<arr.length;i++){
        let item = arr[i];
        if(item.id){
            delete item.id
        }
		if(!item.groupId){
			let extras = item.extras?JSON.parse(item.extras):{}
			let fromId = item.from || item.fromId;
			if(wsFromId!=fromId&& item.isRead!=1&&extras.readState!=1){
			    // readState 2是未读
			    // console.log(314, item, sessionId)
			    sendSocketMsg(item, toUserType)
			}else if(extras.readState!=2){
			    item.isRead = 1
			}
		}
        let index = newArr.findIndex(obj => obj.createTime==item.createTime);
        if(index==-1){
            newArr.push(item)
        }
    }
    function func(a, b){
        return a.createTime-b.createTime;
    }
    newArr.sort(func);

    return newArr;
}

// 聊天发送消息
function sendSocketMsg(msgInfo, wsToType){
// return
    let fromId = msgInfo.from || msgInfo.fromId;
    let tableName = msgInfo.groupId?'togroupmsg':wsToType==1?'totmsg':wsToType==2?'tosmsg':'topmsg'

    let data = {
        "requestEventType": 6,
        "userId": fromId, 
        "createTime": msgInfo.createTime,
        "chatType": 2,
        "sessionId": msgInfo.sessionId
    }
    uni.sendSocketMessage({
        data: JSON.stringify(data),
        success: ()=>{
            let extras = JSON.parse(msgInfo.extras);
            extras.readState = 1
            msgInfo.extras = JSON.stringify(extras)

            getApp().globalData.mysql.isRead(tableName, msgInfo, function(res){
													
            })
        }
    });
}

// 复制文本
function uniCopy({content,success,error}) {
	if(!content) return error('复制的内容不能为空 !')
	content = typeof content === 'string' ? content : content.toString() // 复制内容，必须字符串，数字需要转换为字符串
	/**
	 * 小程序端 和 app端的复制逻辑
	 */
	//#ifndef H5
	uni.setClipboardData({
		data: content,
		success: function() {
			success("复制成功")
		},
		fail:function(){
			success("复制失败")
		}
	});
	//#endif
	
	/**
	 * H5端的复制逻辑
	 */
	// #ifdef H5
	if (!document.queryCommandSupported('copy')) { //为了兼容有些浏览器 queryCommandSupported 的判断
		// 不支持
		error('浏览器不支持')
	}
	let textarea = document.createElement("textarea")
	textarea.value = content
	textarea.readOnly = "readOnly"
	document.body.appendChild(textarea)
	textarea.select() // 选择对象
	textarea.setSelectionRange(0, content.length) //核心
	let result = document.execCommand("copy") // 执行浏览器复制命令
	if(result){
		success("复制成功")
	}else{
		error("复制失败，请检查h5中调用该方法的方式，是不是用户点击的方式调用的，如果不是请改为用户点击的方式触发该方法，因为h5中安全性，不能js直接调用！")
	}	
	textarea.remove()
	// #endif
}

// 通过本地缓存判断消息的红点提示
function showRedDot(newMsgHis, userId){
    uni.hideTabBarRedDot({index: 3})
    for (const key in newMsgHis) {
        
        let data = newMsgHis[key].data && newMsgHis[key].data[0] || {}
        if (newMsgHis[key].count>0&&(key.indexOf(userId)>0 || data.groupId&&key.indexOf(userId)!=-1)) {
            // uni.showTabBarRedDot({index: 3})
        }
    }
    noticeRedDot()
}

// H5 到tabBar页面的时候调用，用于任务和结对消息的红点提示
function noticeRedDot(){
    let dsh = getApp().globalData.bdxs_shbyrwdss||{},
    examinActivity = getApp().globalData.examinActivity || [],
    msgTips = getApp().globalData.msgTips||[];
    if(dsh.bdxs){
        let count = dsh.shbyrwdss.length + dsh.shbydss.length + dsh.bdxs.length;
        if(count>0){
            // uni.showTabBarRedDot({index: 1})
        }
    }
    if(msgTips.length>0 || examinActivity.length>0){
        let count = msgTips.length + examinActivity.length
        if(count>0){
            // uni.showTabBarRedDot({index: 1})
        }else{
            uni.hideTabBarRedDot({index: 1})
        }
    }
    
}

// 确认弹窗
function showModal(title, text, fun, parmas, cancelFun){
    const platform = getApp().globalData.platform
    parmas = parmas || {}
    let confirmText = parmas.confirmText || '确认',
    cancelText = parmas.cancelText || '取消';
    uni.showModal({
        title: title,
        content: text,
        // #ifndef APP-PLUS
        cancelText: cancelText,
        confirmText: confirmText,
        // #endif
        // #ifdef APP-PLUS
        cancelText: platform=='android'?confirmText:cancelText,
        confirmText: platform=='android'?cancelText:confirmText,
        // #endif
        success: (res) => {
            if (res.confirm) {
                // #ifndef APP-PLUS
                fun(parmas)
                // #endif
                // #ifdef APP-PLUS
                if(platform != 'android'){
                    fun(parmas)
                }else{
                    cancelFun&&cancelFun()
                }
                // #endif
            } else if (res.cancel) {
                // #ifdef APP-PLUS
                if(platform == 'android'){
                    fun(parmas)
                }else{
                    cancelFun&&cancelFun()
                }
                // #endif
                // #ifndef APP-PLUS
                cancelFun&&cancelFun()
                // #endif
                
            }
        }
    });
}

// 小黑框提示
function showToast(title){
    uni.showToast({
        title: title,
        icon: 'none',
        duration: 2000,
        mask: true,
        position: 'bottom'
    });
}

// 处理用户的头像显示
function headImage(info){
    if(!info) return
    let str = ''
    let type = info.userType || info.user_type
    if(type == 3){
        return info.wxAvatar
    }
    let sex = 1
    type = type?type:2
    if(info){
        sex = info.sex==2 ? 2 : 1
        str = info.avatarUrl?api.xiaodeObsUrl+info.avatarUrl:''
    }
    if(!str){
        str = `/static/${type==2?`stu${sex}`:'te1'}.png`
    }
    return str;
}

// 输入框表情输入
const emojiList = ['😀', '😁', '😂', '😃', '😄', '😄', '😅', '😆', '😇', '😉', '😊', '🙂', '🙃', '🤣', '😍', '😗', '😘', '😙', '😚', '🤩', '🥰', '🥲', '😋', '😛', '😜', '🤪', '😝', '🤑', '🤭', '🤔', '🤫', '🤐', '🤨', '😑', '😶', '😶‍🌫️', '😏', '😒', '🙄', '😬', '😮‍💨', '🤥', '😌', '😔', '😪', '🤤', '😴', '😷', '🤒', '🤕', '🤢', '🤮', '🤧', '🥵', '🥶', '🥴', '😵', '😵‍💫', '🤯', '🥳', '😎', '🤓', '🧐', '😕', '😟', '🙁', '😭', '😱', '😨', '😰', '😥', '😢', '😣', '😞', '😓', '😩', '😫', '🥱', '😠']

// 聊天列表最新一条消息展示
function emojiName(info, userId){
    // console.log(info)
    if(!info) return
    let type = info.msgType, text = info.content;
    
    let str = text==''?'':type == 1?'[图片]':type==2?'[语音]':type==3?'[视频]':type == 6?'[链接]':type == 7? `[图片]`:type==8?'[文件]':type==9?JSON.parse(text).content:text
    if(type==9){ // @
        let list = JSON.parse(text).users;

        // let id = userId - userType*100000
        if(list.findIndex(item=>item.id == userId )==-1){
            str = str.split('tribute-name').join('tribute-name-gray')
        }
    }
    if(!str){
        let fromId = info.from || info.fromId
        if(userId==fromId){
            str = '你撤回了一条消息'
        }else{
            str = '对方撤回了一条消息'
        }
    }
    return str
}

// 任务模块，是否能编辑，文本框
function editorCont(cont){
    if(!cont){
        return false
    }else{
        return true
    }
    // return JSON.parse(cont)[0].insert&&JSON.parse(cont)[0].insert.length>1?true:JSON.parse(cont)[0].attributes?true:false
}
// def 下载图片
let viewImageI = 1
function getDownloadImage(data, index, that){
    viewImageI = index;
    let content = data.content
    if(data.content[0]!='['){
        content = `["${data.content}"]`
    }
    let extras = JSON.parse(data.extras);
    if(extras.picture&&extras.picture.length == JSON.parse(content).length) {
        previewImage(extras.picture)
        return
    }
    that.api.get('file/getDownloadUrl', {
        fileNames: content,
        isThumbnail: false
    }).then(res=>{
        if(res.data.state != 'ok') return
        let downloadUrl = res.data.downloadUrl || {},
        urls = [];
        urls = Object.values(downloadUrl)
        
        let extras = JSON.parse(data.extras);

        extras.picture = extras.picture?extras.picture:[]
        for(let i=0; i<urls.length; i++){
            
            downloadFile(data, urls[i], urls.length, extras, that)
        }
        

    })
}

function downloadFile(data, downloadUrl, len, extras, that){
    uni.downloadFile({
        url: downloadUrl, //资源
        success: (res) => {
            if (res.statusCode === 200) {
                function pic(path){
                    extras.picture.push(path)
                    
                    that.$set(data, 'extras', JSON.stringify(extras))
                    if(len==extras.picture.length){
                        previewImage(extras.picture)
                        // #ifdef APP-PLUS
                        let tableName = data.groupId?'groupId':that.toUserType==1?'totmsg':'tosmsg'
                        getApp().globalData.mysql.update(tableName, data, function(res){})
                        // #endif
                    }
                    
                }
                // #ifdef H5
                pic(res.tempFilePath)

                // #endif
                // #ifdef APP-PLUS
                uni.saveFile({
                    tempFilePath: res.tempFilePath,
                    success: (res1)=>{
                        let dst_path = plus.io.convertLocalFileSystemURL(res1.savedFilePath)

                        pic(dst_path)

                    }
                })
                // #endif
            }
        }
    });
}

function previewImage(list){
    uni.previewImage({
        current: viewImageI,
        urls: list,
        longPressActions: {
            success: function(data) {
                
            },
            fail: function(err) {
                console.log(err.errMsg);
            }
        }
    });
}
// end 下载图片
// 处理sessionId
function getSessionId(id1, id2){
    id1 = parseInt(id1);
    id2 = parseInt(id2);
    let str = id1<id2?`${id1}-${id2}`:`${id2}-${id1}`
    return str
}
//课程标签的背景颜色 
function tagBgColor(str){
    return str=='高三'?'#FF6010':str=='高二'?str=='全年级'?'#1677FF':'#FF8F1F':'#00B578'
}
function getpx(rpx){
	let width = rpx / 750 * uni.getSystemInfoSync().windowWidth;
    width = width>470?470 : width
    return width;
}
function handleRecomTime(date){
    if(!date) return
    date = date.split('-').join('/')
    date = new Date(date)
    let timeDiff = 0;
    timeDiff = Math.ceil((new Date().getTime() - date.getTime())/1000)
    
    let year = date.getFullYear(), month = date.getMonth(), day = date.getDate();
    // 当前时间
    let curYear = new Date().getFullYear();

    let h = date.getHours();
        h = h < 10 ? `0${h}` : h;
        let m = date.getMinutes();
        m = m < 10 ? `0${m}` : m;
        
    if(timeDiff < 60){
        return '刚刚'
    }else if(timeDiff < (60 * 60)){
        return `${Math.ceil(timeDiff/60)}分钟前`
    }else if(timeDiff>= 60*60 && timeDiff<60*60*24){
        return `${Math.ceil(timeDiff/60/60)}小时前`
    }else if(year == curYear){
        return `${year}年${month+1}月${day}日`
    }else{
        return `${year}年${month+1}月${day}日 ${h}:${m}`
    }
}
// 去往个人主页
function userDetails(accountId, type){
    if(!type){
        let allMembers = uni.getStorageSync('allFindMembers')||[]
        type = allMembers[accountId] ? allMembers[accountId].userType : 2
    }
    let path = type == 1 ?  '/pages/teachers/teachers-details' : '/pages/student/user-details'
    uni.navigateTo({
        url: `${path}?id=${accountId}`
    })
}
// 返回上一页
function goBack(){
    let canNavBack = getCurrentPages()
    if(canNavBack && canNavBack.length > 1){
        uni.navigateBack({
            delta: 1
        })
    }else{
        history.back();
    }
}
export default {
    setSTabBar,
    setTTabBar,
    transitionStyles,
    xiaodeShowFiles,
    initDateDay,
    dateFormat,
    handleTs,
    handleDetailsTs,
    getWeek,
    msgPopup,
    deDuplication,
    sendSocketMsg,
    uniCopy,
    showRedDot,
    noticeRedDot,
    showModal,
    showToast,
    headImage,
    emojiName,
    editorCont,
    getDownloadImage,
    getFileDownloadUrl,
    getpx,
    emojiList,
    getSessionId,
    userDetails,
    tagBgColor,
    handleRecomTime,
    goBack
}